import Dep from './dep'

export default class Watcher {
    constructor(vm,dir, exp,filters, cb) {
        this.cb = cb;
        this.vm = vm;
        this.dir = dir;
        this.exp = exp;
        this.filters = filters;
        // 此处为了触发属性的getter，从而在dep添加自己
        this.value = this.get();
    }

    get() {
        Dep.target = this;    // 将当前订阅者指向自己
        let value = this.vm[this.exp];    // 触发getter，添加自己到属性订阅器中
        Dep.target = null;    // 添加完毕，重置
        return value;
    }

    update() {
        let value = this.vm[this.exp];
        let oldVal = this.value;
        if (value !== oldVal) {
            this.value = value;
            this.cb.call(this.dir, value); // 执行Compile中绑定的回调，更新视图
        }
    }
}

